<?php
/**
 * Created by PhpStorm.
 * User: 李果 En:AdoSir
 * Email: 1334435738@qq.com
 * Date: 2019/12/2 14:37
 */

class AsyMysql {
    public $dbSource = '';
    public $dbConfig = [];
    public function __construct()
    {
        $this->dbSource = new Swoole\Mysql;
        $this->dbConfig = [
            'host' => '47.98.176.141',
            'port' => 3306,
            'user' => 'root',
            'password' => 'mysql20!8',
            'database' => 'test',
            'charset' => 'utf8',
        ];
    }

    public function update()
    {

    }

    public function add()
    {

    }

    public function delete()
    {

    }

    /**
     * mysql 执行逻辑
     * @param $id
     * @param $username
     * @return bool
     */
    public function execute($id, $username)
    {
        //connect
        $this->dbSource->connect($this->dbConfig, function ($db, $result) use ($id, $username) {
            echo "mysql-connect" . PHP_EOL;
            if ($result === false) {
                var_dump($db->connect_error);
                //todo
            }

            // $sql = "select * from test where id = {$id}";
            $sql = "update test set username = '{$username}' where id = {$id}";

            //query
            $db->query($sql, function ($db, $result) {
                //select :查询结果集
                //add update delete : 返回bool类型
                if ($result === false) {
                    //todo
                    var_dump($db->error);
                } elseif ($result === true) {
                    //todo
                } else {
                    var_dump($result);
                }
                $db->close();
            });
        });
        return true;
    }
}

$obj = new AsyMysql();
$flag = $obj->execute(1,'ahao-55555');
var_dump($flag);
echo PHP_EOL;
echo "start" . PHP_EOL;

/**
 * 查看输出顺序，和传统的不相同
 *
 * 应用场景：
 * 比如一个文章页面，数据渲染和页面访问次数，数据渲染完成，再去更新页面访问次数，防止必须更新完访问次数才进行数据渲染，从而提高性能
 */